<?php

namespace app\admin\controller;

use think\facade\View;
use app\BaseController;
use think\facade\Session;
use think\captcha\facade\Captcha;

class Login extends AdminBase {

    /**
     * 覆盖AdminBase下initialize
     */
    public function initialize() {
        if ($this->isLogin()) {
            return $this->redirect(url('admin/index/index'));
        }
    }

    /**
     * 登录页面
     * @return string
     */
    public function index() {
        return View::fetch();
    }

    /**
     * 登录验证
     * @return \think\response\Json
     */
    public function check() {
        if (!$this->request->isPost()) {
            return show(config('status.error'), '请求方式错误');
        }

        // 参数检验 1、原生方式  2、TP6 验证机制
        $username = $this->request->param('username', '', 'trim');
        $password = $this->request->param('password', '', 'trim');
        $captcha = $this->request->param('captcha', '', 'trim');

        $data = [
            'username' => $username,
            'password' => $password,
            'captcha'  => $captcha,
        ];
        //halt($data);
        $validate = new \app\admin\validate\AdminUser();
        if (!$validate->check($data)) {
            return show(config('status.error'), $validate->getError() );
        }

        try {
            $result = (new \app\admin\business\AdminUser())->login($data);
        } catch (\Exception $e) {
            return show(config('status.error'), $e->getMessage());
        }
        p($result);

        if (!$result) {
            return show(config('status.error'), '登录失败');
        }
        return show(config('status.success'), '登录成功');
    }

    /**
     * 退出登录
     * @return \think\response\Redirect
     */
    public function logout() {
        session(config('admin.session_admin'), null);
        return redirect(url('login/index'));
    }
}